package tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description: 257. 二叉树的所有路径
 * User: Li_yizYa
 * Date: 2025/6/1
 * Time: 23:32
 */
public class Solution18 {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        List<Integer> paths = new ArrayList<>();
        traversal(root, paths, ret);
        return ret;
    }
    public void traversal(TreeNode root, List<Integer> paths, List<String> ret) {
        paths.add(root.val);
        // 遇到叶子节点
        if (root.left == null && root.right == null) {
            // 输出
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < paths.size() - 1; i++) {
                sb.append(paths.get(i) + "->");
            }
            sb.append(paths.get(paths.size() - 1));
            ret.add(sb.toString());
            return;
        }
        if (root.left != null) {
            traversal(root.left, paths, ret);
            paths.remove(paths.size() - 1); // 回溯
        }
        if (root.right != null) {
            traversal(root.right, paths, ret);
            paths.remove(paths.size() - 1); // 回溯
        }
    }
    public List<String> binaryTreePaths1(TreeNode root) {
        List<String> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Stack<Object> stack = new Stack<>();
        stack.push(root);
        stack.push(root.val + "");
        while (!stack.isEmpty()) {
            String path = (String)stack.pop();
            TreeNode node = (TreeNode)stack.pop();
            if (node.left == null && node.right == null) {
                ret.add(path);
            }
            if (node.left != null) {
                stack.push(node.left);
                stack.push(path + "->" + node.left.val);
            }
            if (node.right != null) {
                stack.push(node.right);
                stack.push(path + "->" + node.right.val);
            }
        }
        return ret;
    }
}
